import { getOrders, getOrderDetail, createOrder, cancelOrder } from '@/api/orders'

const state = {
  list: [],
  currentOrder: null,
  loading: false,
  hasMore: true,
  statusFilter: 'all'
}

const mutations = {
  SET_ORDERS(state, orders) {
    state.list = orders
  },
  
  APPEND_ORDERS(state, orders) {
    state.list = [...state.list, ...orders]
  },
  
  SET_CURRENT_ORDER(state, order) {
    state.currentOrder = order
  },
  
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  
  SET_HAS_MORE(state, hasMore) {
    state.hasMore = hasMore
  },
  
  SET_STATUS_FILTER(state, status) {
    state.statusFilter = status
  },
  
  UPDATE_ORDER_STATUS(state, { orderId, status }) {
    const order = state.list.find(o => o.id === orderId)
    if (order) {
      order.status = status
    }
    
    if (state.currentOrder && state.currentOrder.id === orderId) {
      state.currentOrder.status = status
    }
  },
  
  ADD_ORDER(state, order) {
    state.list.unshift(order)
  }
}

const actions = {
  // 获取订单列表
  async fetchOrders({ commit }, { page = 1, limit = 20, status, type, refresh = false } = {}) {
    try {
      if (refresh) {
        commit('SET_LOADING', true)
      }
      
      const response = await getOrders({
        page,
        limit,
        status: status === 'all' ? undefined : status,
        type
      })
      
      if (response.success) {
        if (page === 1 || refresh) {
          commit('SET_ORDERS', response.data.list)
        } else {
          commit('APPEND_ORDERS', response.data.list)
        }
        
        commit('SET_HAS_MORE', response.data.hasMore)
        return response.data
      } else {
        throw new Error(response.message)
      }
    } catch (error) {
      console.error('获取订单列表失败:', error)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 获取订单详情
  async fetchOrderDetail({ commit }, orderId) {
    try {
      const response = await getOrderDetail(orderId)
      
      if (response.success) {
        commit('SET_CURRENT_ORDER', response.data)
        return response.data
      } else {
        throw new Error(response.message)
      }
    } catch (error) {
      console.error('获取订单详情失败:', error)
      throw error
    }
  },
  
  // 创建订单
  async createOrder({ commit }, orderData) {
    try {
      const response = await createOrder(orderData)
      
      if (response.success) {
        commit('ADD_ORDER', response.data)
        
        uni.showToast({
          title: '订单创建成功',
          icon: 'success'
        })
        
        return response.data
      } else {
        throw new Error(response.message)
      }
    } catch (error) {
      console.error('创建订单失败:', error)
      uni.showToast({
        title: error.message || '创建订单失败',
        icon: 'none'
      })
      throw error
    }
  },
  
  // 取消订单
  async cancelOrder({ commit }, { orderId, reason }) {
    try {
      const response = await cancelOrder(orderId, reason)
      
      if (response.success) {
        commit('UPDATE_ORDER_STATUS', { orderId, status: 'cancelled' })
        
        uni.showToast({
          title: '订单已取消',
          icon: 'success'
        })
        
        return response.data
      } else {
        throw new Error(response.message)
      }
    } catch (error) {
      console.error('取消订单失败:', error)
      uni.showToast({
        title: error.message || '取消订单失败',
        icon: 'none'
      })
      throw error
    }
  },
  
  // 设置状态筛选
  setStatusFilter({ commit, dispatch }, status) {
    commit('SET_STATUS_FILTER', status)
    // 重新加载订单列表
    return dispatch('fetchOrders', { status, refresh: true })
  }
}

const getters = {
  orders: state => state.list,
  currentOrder: state => state.currentOrder,
  loading: state => state.loading,
  hasMore: state => state.hasMore,
  statusFilter: state => state.statusFilter,
  
  // 按状态筛选订单
  ordersByStatus: state => status => {
    if (status === 'all') return state.list
    return state.list.filter(order => order.status === status)
  },
  
  // 待处理订单数量
  pendingOrdersCount: state => state.list.filter(order => order.status === 'pending').length,
  
  // 进行中订单数量
  processingOrdersCount: state => state.list.filter(order => order.status === 'processing').length,
  
  // 订单状态文本映射
  statusText: () => status => {
    const statusMap = {
      pending: '待处理',
      processing: '处理中',
      completed: '已完成',
      cancelled: '已取消'
    }
    return statusMap[status] || '未知状态'
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}